<?php
 
function ratio($im, $fill=false)
{
	$w=imagesx($im);$h=imagesy($im);$r=$w/$h;$d=100;
	$condition=$fill?$w<$h:$w>$h;
	return $condition 
	       ? array('x'=>$d,'y'=>$d / $r, 'w'=>$w, 'h'=>$h)
		   : array('y'=>$d,'x'=>$d * $r, 'w'=>$w, 'h'=>$h);
}


function spc($x,$sx=320)
{
    return ($x * 12) + 175;
}

function Readff()
{
    $fp=fopen('ffm.out', 'r');
    $fr=fread($fp,filesize('ffm.out'));
    fclose($fp); 
    
    $tmp = explode ("\r", $fr);
    $line = '';
    if (sizeof($tmp)>0)
    {
        while (strlen($line)==0)
            $line = array_pop($tmp);
//    print_r($tmp);
    }
    return $line; 
}

#require('GifMerge.class.php');
print_r($argv);
$videofile =  $argv[1]; 
$ffmpeg = 'ffmpeg';

if ($videofile=='read')
{
    $fp=fopen('ffm.out', 'r');
    $fr=fread($fp,filesize('ffm.out'));
    fclose($fp); 
    
    $tmp = explode ("\r", $fr);
    $line = '';
    while (strlen($line)==0)
        $line = array_pop($tmp);
//    print_r($tmp);
    echo $line;
    exit;
}

ob_start();
passthru("\"{$ffmpeg}\" -i \"{$videofile}\" 2>&1");
$source = ob_get_contents();
ob_end_clean();
//echo $source;

if (preg_match('/Video: (.*),/', $source, $matches))
$video = $matches[1];

if (preg_match('/Duration: (.*?),/', $source, $matches))
$dur = $matches[1];
else
{
    echo "Could not read duration of {$videofile}\n\n"; 
    exit;
}
$imageArray = array(); 
$duration_array = split(':', $dur);
$duration = $duration_array[0] * 3600 + $duration_array[1] * 60 + $duration_array[2];
if ($duration < 30)
{
    exit;
}
echo "File is {$duration} seconds in duration. Muxing...\n\n";
//echo $video;

//// exit;
//
$image = "{$videofile}.jpeg";
$c=("\"{$ffmpeg}\" -i \"{$videofile}\" -vcodec mjpeg -vframes 1 -ss 15 -an -f rawvideo -s 320x240 \"{$image}\"");
echo $c;
passthru($c); 
 
exit;

//echo "$image";

      $command = "ffmpeg -i {$videofile} -vpre medium -s 320x240 -r 30000/1001 -b 200k -bt 240k -vcodec libx264 -coder 0 -bf 0 " .
          "-flags2 -wpred-dct8x8 -level 13 -maxrate 768k -bufsize 3M -acodec libfaac -ac 2 -ar 48000 -ab 192k {$videofile}.m4v";
      $command = "ffmpeg -i {$videofile} -f mp4 -vcodec libx264 -vpre default " .
       "-acodec libfaac -bufsize 1835k " .
       "-b 256k {$videofile}-3.m4v";
  //    $command = "ffmpeg -i $videofile -s 320x240 -r 30000/1001 -b 200k -bt 240k -vcodec libx264 -coder 0 -bf 0 -refs 1 -flags2 -wpred-dct8x8 -level 30 -maxrate 10M -bufsize 10M -acodec libfaac -ac 2 -ar 48000 -ab 192k {$videofile}.m4v";
$id = run_in_background($command);

echo $id;
while (is_process_running($id))
{
    echo Readff();
}
exit;


    function run_in_background($Command, $Priority = 0)
    {
        unlink ('ffm.out');
        if($Priority)
            $PID = shell_exec("nohup nice -n $Priority $Command > /dev/null & echo $!");
        else
            $PID = shell_exec("nohup $Command > /var/www/html/ffm.out & echo $!");
        return($PID);
    }

    function is_process_running($PID)
    {
        exec("ps $PID", $ProcessState);
        return(count($ProcessState) >= 2);
    }
    
    
$interval = floor($duration/10);
 
for ($x=0;$x<sizeof($imageArray);$x++)
    if (file_exists ($imageArray[$x]))
        unlink ($imageArray[$x]);

for ($i=$interval > 30 ? 30 : $interval;$i<$duration;$i+=$interval)
{
    $image = "{$videofile}_{$i}.jpg";
    $imageArray[] = $image;
    $c=("\"{$ffmpeg}\" -i \"{$videofile}\" -vcodec mjpeg -vframes 1 -ss {$i} -an -f rawvideo -s 320x240 \"{$image}\"");
    echo $c;
    passthru($c); 
}

echo GenerateAnimation ($imageArray, $videofile);
$im = imagecreatefromjpeg ($imageArray[0]);
imagejpeg ($im, "{$videofile}.jpg", 100); 
imagedestroy ($im);
for ($x=0;$x<sizeof($imageArray);$x++)
    unlink ($imageArray[$x]);

function GenerateAnimation ($imageArray, $videofile)
{
    $__i=array();
    $__d=array();
    $__x=array();
    $__y=array(); 
   

# begin frames
    for ($x=0;$x<sizeof($imageArray);$x++)
    {  
        ob_start();

        $im = imagecreatefromjpeg ($imageArray[$x]);
        $sx = imagesx ($im);
        $sy = imagesy ($im);
        $dx = spc($x);
        $dy = $sy - 20;
        $back = imagecolorallocatealpha ($im, 75,75,75, 20);//imagecolorallocatealpha  ( resource $image  , int $red  , int $green  , int $blue  , int $alpha  )
        $gray = imagecolorallocate ($im, 200,200,200);
        $pink = imagecolorallocate ($im, 200,88,124);

            imagefilledrectangle  ( $im  , 170  , $dy - 4  , 300  , $dy + 6  , $back  ); 


        for ($d=0;$d<sizeof($imageArray);$d++)
        {
            $gx = spc($d);
            imagefilledrectangle  ( $im  , $gx  , $dy  , $gx + 10  , $dy + 2  , $gray  ); 
        }

        imagefilledrectangle  ( $im  , $dx  , $dy  , $dx + 10  , $dy + 2  , $pink  ); 

 
        $sm = resizeImage ($im,$sx,$sy,.5);


        imagegif($sm);  
        imagedestroy($sm);
        imagedestroy($im);
        $__i[] = ob_get_contents();
	ob_end_clean();
 
        $__x[] = 0;
        $__y[] = 0; 
        $__d[] = 45;  
             
             
    }  
		
    ob_start(); 


    $gifmerge    = new GifMerge($__i, 1, 1, 1, -10, $__d, 2, $__x, $__y, 'C_MEMORY');
    echo $gifmerge -> getAnimation();   
    $gif = ob_get_contents();
    ob_end_clean();

    $imagePath = $videofile.'.gif'; 
    $fo=fopen($imagePath, 'w');
    fwrite ($fo, $gif);
    fclose($fo);
    return $imagePath;
}


?>